package com.zidian.leader.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.zidian.leader.R;
import com.zidian.leader.common.util.ColorConstants;
import com.zidian.leader.common.util.StringConstants;
import com.zidian.leader.entity.ColleagueEvaResult;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 同行/督导评价adapter
 * Created by GongCheng on 2017/1/9.
 */

public class ColleagueEvaAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int TYPE_TOP = 0;
    private final static int TYPE_ITEM = 1;

    private List<ColleagueEvaResult.DataBean> list;

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_TOP) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bar_chart, parent, false);
            return new TopViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_colleague_eva_detail, parent, false);
            return new ItemViewHolder(view);
        }
    }

    public interface OnItemClickListener{
        void onClick(String indexName, float indexScore);
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof TopViewHolder) {
            initBarChart(((TopViewHolder) holder).colleagueBarChart);
            ((TopViewHolder) holder).colleagueBarChart.setData(getBarData());
            ((TopViewHolder) holder).colleagueBarChart.invalidate();
        } else if (holder instanceof ItemViewHolder) {
            ((ItemViewHolder) holder).evaluateColor.setBackgroundColor(ColorConstants.CHART_COLORS[position - 1]);
            ((ItemViewHolder) holder).evaluateScored.setText(list.get(position - 1).getIndexScore() + "");
            ((ItemViewHolder) holder).evaluateType.setText(list.get(position - 1).getIndexName());
            StringBuilder sb = new StringBuilder();

            if (list.get(position - 1).getTwoIndexList().size() == 1) {
                sb.append(list.get(position - 1).getTwoIndexList().get(0) );
            } else {
                sb.append(list.get(position - 1).getTwoIndexList().get(0)).append("、");
            }
            for (int i = 1; i < list.get(position - 1).getTwoIndexList().size(); i++) {
                if (i == list.get(position - 1).getTwoIndexList().size() - 1) {
                    sb.append(list.get(position - 1).getTwoIndexList().get(i));
                } else {
                    sb.append(list.get(position - 1).getTwoIndexList().get(i)).append("、");
                }
            }
            ((ItemViewHolder) holder).evaluateTag.setText(sb.toString());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onClick(list.get(holder.getAdapterPosition() - 1).getIndexName(),
                                list.get(holder.getAdapterPosition() - 1).getIndexScore());
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_TOP;
        } else {
            return TYPE_ITEM;
        }
    }

    /**
     * 初始化条形图
     *
     * @param chart 条形图
     */
    private void initBarChart(BarChart chart) {
        chart.setDescription(null);
        //设置拦截所有触摸事件
        chart.setTouchEnabled(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(5);
        xAxis.setTextSize(10f);
        //X轴Value设计
//        xAxis.setValueFormatter(valueFormatter);
        xAxis.setGranularity(1);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return StringConstants.STRING_EMPTY;
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        //Y轴左侧
        YAxis yl = chart.getAxisLeft();
        yl.setDrawAxisLine(true);
        yl.setDrawGridLines(false);
        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //Y轴右侧
        YAxis yr = chart.getAxisRight();
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setAxisMinimum(0f);
        yr.setEnabled(false);
        chart.animateY(1500);
        //取消图表说明设置
        Legend l = chart.getLegend();
        l.setEnabled(false);
    }

    /**
     * 得到BarChart的data
     *
     * @return 饼状图
     */
    private BarData getBarData() {
        List<BarEntry> barEntries = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            barEntries.add(new BarEntry(i + 1, decimal(list.get(i).getIndexScore())));
        }
        BarDataSet dataSet = new BarDataSet(barEntries, "BarChart");
        dataSet.setColors(ColorConstants.CHART_COLORS);
        BarData barData = new BarData(dataSet);
        barData.setBarWidth(0.3f);
        barData.setValueTextSize(12);
        return barData;
    }

    /**
     * 精确到小数点后2位
     *
     * @param f
     * @return
     */
    private float decimal(float f) {
        DecimalFormat decimalFormat = new DecimalFormat("##0.00");
        String format = decimalFormat.format(f);
        return Float.parseFloat(format);
    }

    public void setList(List<ColleagueEvaResult.DataBean> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    static class TopViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.colleague_bar_chart)
        BarChart colleagueBarChart;

        TopViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.evaluate_color)
        ImageView evaluateColor;
        @Bind(R.id.evaluate_type)
        TextView evaluateType;
        @Bind(R.id.evaluate_tag)
        TextView evaluateTag;
        @Bind(R.id.evaluate_scored)
        TextView evaluateScored;

        ItemViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
